import { defineStore } from "pinia"
import { computed, onMounted, reactive, ref } from "vue"
import { orderNo } from "@/utils/orderNo"
import { MessagePlugin } from "tdesign-vue-next"
import { apiUrl, get, post } from "@/utils/api"


export const useBuyStore = defineStore("buy", () => {
  const shopInformation = ref([
    {
      id: "", // Application id
      price: "", // Application price
      name: "", // Application name
      description: "", // Application description
      img: "" // Application image
    }
  ])
  const orderInformation = reactive({
    uid: "",
    pid: "",
    title: "",
    total: "",
    order: "",
    type: 0
  })
  const payTypeDialogVisible = ref(false)
  const buyAuthorization = (item: any) => {
    payTypeDialogVisible.value = true
    orderInformation.title = item.name
    orderInformation.total = item.price
    orderInformation.order = orderNo()
    orderInformation.pid = item.id
    // 再获取uid
  }
  const getList = async () => {
    shopInformation.value = await get("/api/program/getAll")
  }
  const isOpenPayment = async () => {
    const aliPayIsOpen = await get("/api/aliPay/isOpen")
    aliPay.cardVisible.value = aliPayIsOpen.isOpen === 1
    const wechatPayIsOpen = await get("/api/wechatPay/isOpen")
    wechatPay.cardVisible.value = wechatPayIsOpen.isOpen === 1
  }

  onMounted(async () => {
    await getList()
    await isOpenPayment()
  })
  const aliPay = {
    codeVisible: ref(false),
    cardVisible: ref(),
    url: ref(),
    loading: ref(),
    key: ref(0),
    doPay: () => {
      payTypeDialogVisible.value = false
      aliPay.codeVisible.value = true
      aliPay.loading.value = true
      const { total, pid, title, order } = orderInformation
      aliPay.url.value = apiUrl(`/api/aliPay/pay?total=${total}&pid=${pid}&title=${title}&order=${order}`)
      aliPay.key.value ++
      request(orderInformation.order)
    }
  }
  const wechatPay = {
    codeVisible: ref(false),
    cardVisible: ref(),
    url: ref(),
    loading: ref(),
    key: ref(0),
    doPay: async () => {
      payTypeDialogVisible.value = false
      wechatPay.codeVisible.value = true
      wechatPay.loading.value = true
      const { total, pid, title, order } = orderInformation
      wechatPay.url.value = apiUrl(`/api/wechatPay/pay?total=${total}&pid=${pid}&title=${title}&order=${order}`)
      wechatPay.key.value ++
      request(orderInformation.order)
    }
  }
  const isStopPolling = computed(()=>{
    return !aliPay.codeVisible.value && !wechatPay.codeVisible.value
  })
  // Payment result polling
  const request = (order: string) => {
    const pollInterval = 2000 // Polling frequency 2s per time
    const pollDuration = 180000 // Polling duration 3min
    const startTime = Date.now()
    const pollingInterval = setInterval(async () => {
      if (Date.now() - startTime > pollDuration) {
        console.log("请求超时")
        await MessagePlugin("warning", "支付超时！")
        clearInterval(pollingInterval)
        closeCodeVisible()
        return
      }
      if (isStopPolling.value) {
        console.log("取消支付")
        await MessagePlugin("warning", "取消支付！")
        clearInterval(pollingInterval)
        return
      }
      const response = await post("/api/order/isPaid", { order })
      if (response.status === "success") {
        console.log("请求成功")
        closeCodeVisible()
        await MessagePlugin("success", "支付成功，请前往用户中心管理授权！", 5000)
        clearInterval(pollingInterval)
        return
      }
      console.log("请求继续")
    }, pollInterval)
    const closeCodeVisible = () => {
      wechatPay.codeVisible.value = false
      aliPay.codeVisible.value = false
    }
  }

  return { shopInformation, payTypeDialogVisible, aliPay, buyAuthorization, wechatPay, isStopPolling }
})
